﻿using System;
using System.Xml.Linq;
using System.Xml;
using WinForm_LogSystem;
using System.IO;
namespace WinForm_ConfigSystem
{
    public class ConfigSystem
    {
        /// <summary>
        /// 配置文件名字
        /// </summary>
        public string configFileName;

        /// <summary>
        /// 配置文件
        /// </summary>
        public XDocument configFile;

        /// <summary>
        /// 默认配置
        /// </summary>
        public XElement? defaultConfig;
        /// <summary>
        /// 输出日志事件
        /// </summary>
        public event EventHandler<LogArgs> OutputLog;
        
        /// <summary>
        /// 创建一个实例，创建完后需要使用LoadConfigFile
        /// </summary>
        /// <param name="configFileName">配置文件名字</param>
        /// <param name="defaultConfig">默认配置，可为null,最好要有</param>
        public ConfigSystem(string configFileName, XElement? defaultConfig)
        {
            this.configFileName = configFileName;
            this.defaultConfig = defaultConfig;
        }
        /// <summary>
        /// 加载配置文件
        /// </summary>
        public void LoadConfigFile()
        {
            try
            {
                configFile = XDocument.Load(configFileName);
            }
            catch(FileNotFoundException exp)
            {
                OutputLog(this,new LogArgs("没有找到配置文件"+exp.FileName+".准备重新生成配置文件", LogState.Warning));
                CreateDefaultConfig();
            }
            catch(XmlException exp)
            {
                OutputLog(this, new LogArgs("配置文件损坏或者不是xml文件!"+exp.Message, LogState.Warning));

                //备份原来错误的配置文件
                Random random= new Random();
                double randomFileName=random.NextDouble();
                string wrongConfigFileName = "WrongConfigFile" + randomFileName.ToString("F10")+".xml";
                File.Copy(configFileName, wrongConfigFileName);
                OutputLog(this, new LogArgs("原配置文件已经改名为:" + wrongConfigFileName + ".准备重新生成配置文件", LogState.Warning));

                CreateDefaultConfig();
            }
        }

        /// <summary>
        /// 生成默认配置文件，defaultConfig不可以为null
        /// </summary>
        public void CreateDefaultConfig()
        {
            if(defaultConfig==null)
            {
                OutputLog(this, new LogArgs("默认配置为空！无法重新生成配置文件", LogState.Warning));
            }
            else
            {
                configFile = new XDocument(defaultConfig);
                SaveConfigFile();
                OutputLog(this, new LogArgs("已经重新生成配置文件"+configFileName, LogState.Normal));
            }
        }
        /// <summary>
        /// 保存配置文件
        /// </summary>
        public void SaveConfigFile()
        {
            FileStream fs =new FileStream(configFileName,FileMode.Create);
            configFile.Save(fs);
            fs.Close();
        }
    }
}
